/**
 * @Title: FileUtils.java
 * @Package: com.jason.bluetooth.fingerprint.utils
 * @Descripton: TODO
 * @Author: Administrator zhangyujn1989ok@gmail.com
 * @Date: 2014年11月4日11:32:35
 * @Version: V1.0
 */
package net.hzlj.platform.enterprise.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.icu.util.Output;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.common.Constant;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/**
 * @ClassName: FileUtils
 * @Description: 文件处理
 * @Author: Administrator zhangyujn1989ok@gmail.com
 * @Date: 2014年11月4日11:32:21
 */
public class FileUtils {

	private static final String TAG = FileUtils.class.getSimpleName();

	/***
	 * 新建层级文件夹
	 * Android 在一些机型上面无法使用mkdirs
	 * /storage/0798-12FD/EP_ChangSha_Hosting/Log/Log-20161129
	 * @param context		上线文菜单
	 * @param fileName		文件夹名称数组{"A","B"}
     * @return
     */
	public static File getDiskCacheDir(Context context, String... fileName){
		final String rootPath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir()
				.getPath();

		final File dir = new File(rootPath + getFilePath(fileName));
		if (dir.exists()) {
			if (!dir.isDirectory()) {
				dir.delete();
			} else {
				return dir;
			}
		} else {
			File rootFile = new File(rootPath);
			if (fileName != null && fileName.length > 0){
				for (int i = 0; i < fileName.length; i++) {
					 File child = new File(rootFile,fileName[i]);
					if (!child.exists()){
						child.mkdir();
					}
					rootFile = child;
				}
			}
		}
		return dir;
	}

	public static String getFilePath(String... fileName){
		if (fileName == null || fileName.length == 0){
			fileName = new String[]{Constant.BASE_FOLDER};
		}
		StringBuilder path = new StringBuilder();
		for (int i = 0; i < fileName.length; i++) {
			path.append(File.separator).append(fileName[i]);
		}
		return path.toString();
	}

	public static File getDiskCacheDir(Context context, String rootFileName) {
		final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir()
				.getPath();
		final File dir = new File(cachePath + File.separator + rootFileName);
		if (dir.exists()) {
			if (!dir.isDirectory()) {
				dir.delete();
			} else {
				return dir;
			}
		} else {
			dir.mkdir();
		}
		return dir;
	}

	/**
	 * 根据指定路径创建文件
	 * @param path
	 */
	public static File createFile(String path){
		File file = new File(path);
		if (!file.exists()){
			String directory = path.substring(0, path.lastIndexOf("/"));
			File dirFile = new File(directory);
			if (!dirFile.exists())
				dirFile.mkdirs();
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 重命名文件,除文件名外文件路径必须保持一致
	 * @param oldPath
	 * @param newPath
	 */
	public static void renameTo(String oldPath, String newPath){
		File oldFile = new File(oldPath);
		File newFile = new File(newPath);
		oldFile.renameTo(newFile);
	}

	@TargetApi(9)
	public static boolean isExternalStorageRemovable() {
		if (hasGingerbread()) {
			return Environment.isExternalStorageRemovable();
		}
		return true;
	}

	/**
	 * 获得文件长度
	 * @param filePath
	 * @return
	 */
	public static int getFileLength(String filePath) {
		if (!isExist(filePath)) {
			return 0;
		}

		File file = new File(filePath);
		int length = (int) file.length();
		return length;
	}

	/**
	 * 是否存在
	 *
	 * @param filepath
	 * @return
	 */
	public static boolean isExist(String filepath) {
		File file = new File(filepath);
		return file.isFile();
	}

	/**
	 * 检查文件是否已经存在
	 * @param filePath
	 * @return
	 */
	public static boolean checkFileExists(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			return true;
		} else
			return false;
	}

	@TargetApi(8)
	public static File getExternalCacheDir(Context context) {
		return new File(Environment.getExternalStorageDirectory().getPath());
	}

	public static boolean hasFroyo() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
	}

	public static boolean hasGingerbread() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}

	public static boolean hasHoneycombMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
	}

	public static boolean hasJellyBean() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
	}

	/***
	 * 	文件复制（高效）
	 * @param sourceFle	原文件
	 * @param targetFile	目标文件
     */
	public static void fileChannelCopy(File sourceFle, File targetFile) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			if (!targetFile.exists()){
				targetFile.createNewFile();
			}
			fi = new FileInputStream(sourceFle);
			fo = new FileOutputStream(targetFile);
			in = fi.getChannel();//得到对应的文件通道
			out = fo.getChannel();//得到对应的文件通道
			in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/***
	 * 文件复制
	 * @param sourceFle
	 * @param targetFile
     */
	public static void copy(File sourceFle, File targetFile){
		InputStream fis = null;
		OutputStream fos = null;
		try {
			if (!targetFile.exists()){
				targetFile.createNewFile();
			}
			fis = new BufferedInputStream(new FileInputStream(sourceFle));
			fos = new BufferedOutputStream(new FileOutputStream(targetFile));
			byte [] buf = new byte[2048];
			int i;
			while ((i = fis.read(buf)) != -1){
				fos.write(buf,0,i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
